package com.th.coupon.serialization;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.th.coupon.entity.Coupon;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * 自定义优惠卷实体序列化
 * @author 涂航
 */
public class CouponSerialize extends JsonSerializer<Coupon> {
    @Override
    public void serialize(Coupon value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        //开始序列化
        gen.writeStartObject();
        gen.writeStringField("id",value.getId().toString());
        gen.writeStringField("templateId",value.getTemplateId().toString());
        gen.writeStringField("userId",
                value.getUserId().toString());
        gen.writeStringField("couponCode",
                value.getCouponCode());
        gen.writeStringField("assignTime",
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(value.getAssignTime()));
        //优惠卷模板名称
        gen.writeStringField("name",
                value.getTemplateSDK().getName());
        //优惠卷logo
        gen.writeStringField("logo",
                value.getTemplateSDK().getLogo());
        //优惠卷模板描述
        gen.writeStringField("desc",
                value.getTemplateSDK().getDesc());
        //优惠卷过期规则
        gen.writeStringField("expiration",
                JSON.toJSONString(
                        value.getTemplateSDK().getRule().getExpiration()));
        //优惠卷折扣规则
        gen.writeStringField("discount",
                JSON.toJSONString(
                        value.getTemplateSDK().getRule().getDiscount()));
        //优惠卷使用范围
        gen.writeStringField("usage",
                JSON.toJSONString(value.getTemplateSDK().getRule().getUsage()));

        //借宿序列化
        gen.writeEndObject();


    }
}
